var freeswitchUser;

var myUA;

var incomingSession;

var timeOutTask;

var interval;

var sipSession;

var remoteAudio = document.getElementById("remoteAudio");

var localAudio = document.getElementById("localAudio");

function initUa(password) {
    //alert(freeswitchWs);
    var uaConfig = {
        uri: freeswitchUser + "@" + userurl,
        transportOptions: {
            wsServers: freeswitchWs
        },
        authorizationUser: freeswitchUser,
        displayName: freeswitchUser,
        password: password,
        log: {
            builtinEnabled: false
        },
        //traceSip:true,
        register: true
    };


    myUA = new SIP.UA(uaConfig);
    //ws链接成功调用
    myUA.on("connected", function () {
        alert("websocket连接成功");

        console.log("freeswitchLog:  websocket连接成功: " + uaConfig.wsServers);
    });
//ws链接失败调用
    myUA.on("disconnected", function () {
        alert("websocket连接失败");
        console.log("freeswitchLog:  websocket连接失败: " + uaConfig.wsServers);
    });

//注册成功调用
    myUA.on("registered", function () {
        console.log("freeswitchLog:  " + uaConfig.authorizationUser + "用户注册成功");
        upgradeDOM();
        //先清除旧的定时任务,再重新执行
        window.clearInterval(interval);
        setUAInterval();
        callPhone();
    });

//取消时候调用
    myUA.on("unregistered", function () {
        console.log("freeswitchLog:  " + uaConfig.authorizationUser + "用户取消注册");
        window.clearInterval(interval);
    });


    /**
     *接受入站
     */
    myUA.on("invite", function (thisIncomingSession) {
        alert("接受入站");
        incomingSession = thisIncomingSession;
        initSession(incomingSession);
    });

    myUA.on("accept", function (session) {
        session.accept();
    });

}
/**
 * 初始化Session
 */
function initSession(initSession) {

    initSession.accept({
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: true,
                video: false
            }
        }/*,
        media:{
            remote :{
                audio : $("#remoteAudio").get(0)
            }
        }
    },initSession*/});

    sipSession = initSession;

    sipSession.on("accepted",function () {
        //我们需要检查对等连接以确定添加了哪个轨道

        var pc = sipSession.sessionDescriptionHandler.peerConnection;
        console.log(pc);
        console.log(pc.getLocalStreams());
        //获取远程轨道
        var remoteStream = new MediaStream();
        pc.getReceivers().forEach(function(receiver){
            remoteStream.addTrack(receiver.track);
        });
        remoteAudio.srcObject = remoteStream;
        remoteAudio.play();

        //获取本地轨道
        var localStream = new MediaStream();
        pc.getSenders().forEach(function(sender){
            localStream.addTrack(sender.track);
        });
        localAudio.srcObject = localStream;
        //localAudio.play();
    });

    initSession.on("accepted", function (data) {
        //console.log("freeswitchLog: 收到请求成功的最终回复:"+data.substr(data.search(/[2][0-9][0-9]/),3));
        clearTimeout(timeOutTask);
        outgoingStop()
    });
}


/**
 * 设置定时任务,每隔20秒检测
 */
function setUAInterval() {

    console.log("freeswitchlog:  开启定时检测UA任务")

    interval = setInterval("checkUAStatus()", 20000)
}

/**
 * 定时检测UA的健康
 */
function checkUAStatus() {
    if (myUA != null && myUA != undefined) {
        //var isConnected = myUA.isConnected();
        var isRegistered = myUA.isRegistered();

        if (/*!isConnected ||*/ !isRegistered) {
            console.log("freeswitchLog:  连接或者注册异常,将重新连接")
            myUA.start();
        } else {
            console.log("freeswitchLog:  连接和注册正常,每20秒检测一次")
            //myUA.register();
        }
    }

}

/**
 * 点击登录
 */
$("#login").click(function () {
    if ($("#login").val() == "登录") {
        freeswitchUser = $("#mainCallPhone").val();

        initUa($("#password").val());
    } else if ($("#login").val() == "注销") {
        myUA.unregister();
        myUA = null;
        demotionDom()
    }
});


window.onload = function () {
    freeswitchUser = username;
    //注册ua对象
   initUa("ihkyanfa");
/*   if(!myUA.isRegistered()){
       console.log("msg:"+msg);
       window.Android.CallIpStateError({"msg":msg});
   }*/
};

/**
 * 渲染页面
 */
function upgradeDOM() {
    $("#status").text("已登录").css("color", "green");
    $(".initDom").attr("disabled", false);
    $("#callBtn,#interrupCall").css("display", "inline");
    $("#passwordTr").hide();
    $("#login").val("注销");
    $("#mainCallPhone").attr("readonly", true);
    clearTimeout(timeOutTask);
}

/**
 * 页面恢复初始状态
 */
function demotionDom() {
    $("#status").text("未登录").css("color", "red");
    $(".initDom").attr("disabled", true);
    $("#callBtn,#interrupCall").css("display", "none");
    $("#passwordTr").show();
    $("#login").val("登录");
    $("#mainCallPhone").attr("readonly", false);
}



/**
 * 铃声停止
 */
function outgoingStop() {

    $("#bell").get(0).pause();
}

/**
 *铃声开始
 */
function outgoingRing() {
    $("#bell").get(0).play();
};

/**
 * 响铃太久
 * @param inComingSession
 */
function connectTimeOut() {

    if (incomingSession == null || incomingSession == undefined) {
        console.log("freeswitchLog:  连接超过30秒,通话将自动关闭");
        outgoingStop();
    } else {
        console.log("freeswitchLog:  连接超过30秒,通话将自动关闭");
        incomingSession.bye();
        incomingSession = null;
        outgoingStop();
    }
    $("#callBtn").css("display", "inline-block");
}